//
//  SSStatusListModel.swift
//  weibo
//
//  Created by 邵帅 on 16/6/27.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit
import SDWebImage

class SSStatusListModel: NSObject {
    
    static let shareInstance: SSStatusListModel = SSStatusListModel()
        
    private override init(){
        
        
    }

    
    lazy var statusList: [SSStatusCellModel] = [SSStatusCellModel]()

    
    
    func loadData(since_id: Int,max_id: Int,success: (count: Int)->(),falsed:()->()){
        
        readData(since_id, max_id: max_id) { (array) in
            
            if array.count > 0 {
                
                var arr = [SSStatusCellModel]()
                
                // 字典转模型
                for dict in array {
                    
                    let model = SSStatusModel(dict: dict)
                    
                    arr.append(SSStatusCellModel(model: model))
                }
                
                // 拼接数据
                if max_id > 0 {
                    
                    
                    self.statusList = self.statusList + arr
                }else {
                    
                    self.statusList = arr + self.statusList
                }
                
                
                success(count: -1)
               
            }else {
                
                // 从网络加载
                self.netloadData(since_id, max_id: max_id, success: success, falsed: falsed)
            }
            
        }
    
    }
    
    func netloadData(since_id: Int,max_id: Int,success: (count: Int)->(),falsed:()->()) {
        
        guard let access_token = SSOauthModel.shareInstance.access_token else {
            return
        }
        
        
        let params = ["access_token":access_token,
                      "since_id": since_id,
                      "max_id": max_id]
        
        SSHTTPClient.shareInstance.request(.GET, URLString: "https://api.weibo.com/2/statuses/home_timeline.json", parameters: params, progress: nil, success: { (_, JSON) in
            
            guard let json = JSON as? [String: AnyObject] else {
                return
            }
            
            guard let arr = json["statuses"] as? [[String: AnyObject]] else {
                return
            }
            
            // 存储数据到数据库
            self.saveData(arr)
            
            
            let group = dispatch_group_create()
            
            // 定义一个临时数组，接收数据进行拼接
            var temp = [SSStatusCellModel]()
            
            
            for status in arr {
                
                let model = SSStatusModel(dict: status)
                
                // 如果图片的数组 == 1时，下载图片
                if let urls = model.picture_urls == nil ? model.retweet_status?.picture_urls : model.picture_urls where urls.count == 1{
                    
                    dispatch_group_enter(group)
                    
                    if let urlString = urls.first?.model?.thumbnail_pic, let url = NSURL(string: urlString) {
                        
                        SDWebImageManager.sharedManager().downloadWithURL(url, options: [], progress: nil, completed: { (_, _, _, _) in
                            
                            dispatch_group_leave(group)
                        })
                        
                        
                    }
                    
                }
                
                // 添加到临时数组
                temp.append(SSStatusCellModel(model: model))
                
//                self.statusList.append(SSStatusCellModel(model: model))
                
            }
            
            // 判断一下，加载更多的时候，拼接数组
            if max_id > 0 {
                
                self.statusList = self.statusList + temp
            } else {
                
                self.statusList = temp + self.statusList
            }
            
            
            // 所有单张图片下载完成，再回调
            dispatch_group_notify(group, dispatch_get_main_queue(), { 
                
                success(count: temp.count)
            })
            
            
        }) { (_, error) in
            
            print(error)
            
            falsed()
        }
        
    }
    
    
    
    // 数据存储到数据库方法
    private func saveData(array: [[String: AnyObject]]) {
        
        let sql = "INSERT OR REPLACE INTO T_Status (status,statusId,userId) VALUES (?,?,?);"
        
        guard let userId = SSOauthModel.shareInstance.userModel?.uid else {
            return
        }
        
        for dict in array{
            
            guard let statusId = dict["id"] as? Int else {
                
                return
            }
            
            // 需要把字典转换成字符串进行存储，取出来时才有值
            guard let data = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) else {
                return
            }
            
            guard let str = String(data: data, encoding: NSUTF8StringEncoding) else {
                
                return
            }
            
            
            SSDBManager.shareInstance.queue.inTransaction({ (db, rollBack) in
                
                db.executeUpdate(sql, withArgumentsInArray: [str,statusId,userId])
                
                printLog("插入成功")
            })
            
        }
    }
    
    
    // 读取数据库的数据
    private func readData(since_id: Int,max_id: Int,closure:(array: [[String: AnyObject]])->()){
        
        var sql = "SELECT status,statusId FROM T_Status WHERE userId = 5829345367 AND \n"
        
        if max_id > 0 {
            
            sql = sql + "statusId < \(max_id) \n"
            
        }else {
            
            sql = sql + "statusId > \(since_id) \n"
        }
        
        sql = sql + "ORDER BY statusId DESC LIMIT 20"
        
        SSDBManager.shareInstance.queue.inDatabase { (db) in
            
            let result = db.executeQuery(sql, withArgumentsInArray: nil)
            
            // 定义数组，用来接收数据库中由字符串转成的字典
            var temp: [[String: AnyObject]] = [[String: AnyObject]]()
            
            while result.next() {
                
                // 对应的字段
                guard let statusString = result.objectForColumnName("status") as? String else {
                    return
                }
                
                guard let data = statusString.dataUsingEncoding(NSUTF8StringEncoding) else {
                    return
                }
                
                guard let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
                as? [String: AnyObject] else {
                    return
                }
                
                temp.append(dict!)
            }
            
            closure(array: temp)
        }
        
        
    }

}
